package com.xiao.framework.ds.autoconfigure.context;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @author <a href="mailto:xiaoquanidea@163.com">hutiquan</a>
 * @since 2019-08-24 18:18
 */
public final class DataSourceHolder {

  /**
   * 模拟栈FIFO,例如abc三个方法,a调用b,b调用c,传统的设置到当前线程的做法无法满足,
   * 需要模拟栈 先进后出,后进先出
   * a -> b -> c -> b -> a
   */
  private static final ThreadLocal<Deque<String>> CURRENT_DATASOURCE_DEMETER_KEY = ThreadLocal.withInitial(ArrayDeque::new);

  //获取
  public static String get(){
    return CURRENT_DATASOURCE_DEMETER_KEY.get().peek();
  }

  //压栈
  public static void push(String dataSource){
    CURRENT_DATASOURCE_DEMETER_KEY.get().push(dataSource);
  }

  //弹栈
  public static String pop(){
    Deque<String> demeterKeys = CURRENT_DATASOURCE_DEMETER_KEY.get();
    String demeterKey = demeterKeys.pop();
    if (demeterKeys.isEmpty()) {
      CURRENT_DATASOURCE_DEMETER_KEY.remove();
    }
    return demeterKey;
  }

  public static void clear(){
    CURRENT_DATASOURCE_DEMETER_KEY.remove();
  }
}
